<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <el-card v-model="discipline" class="box-card" style="margin-top: 11px;">
          <div v-for="(item,index) in dict.standard_drawing_discipline" :key="index" :class="['item', { 'active': item.value === discipline }]" @click="changeItem(item)">{{ item.label }}</div>
        </el-card>
      </el-col>
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <crudOperation :disabled-add="discipline == ''" :permission="permission">
          <el-button
            slot="right"
            class="filter-item"
            type="primary"
            size="mini"
            icon="el-icon-setting"
            :disabled="discipline == ''"
            @click="configGroup"
          >配置组合</el-button>
          <el-button
            slot="right"
            class="filter-item"
            type="primary"
            size="mini"
            icon="el-icon-tickets"
            @click="toggleShowLog"
          >日志</el-button>
        </crudOperation>
        <div class="uifix-table-tips">提示：节点表中的必做项、排除项不可加入组合</div>
        <!--表单组件-->
        <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="700px">
          <el-form ref="form" :model="form" :rules="rules" size="small" label-width="150px">
            <el-form-item label="视图/模型/图纸类别" prop="drawingName" class="form-item-margin">
              <el-input v-model="form.drawingName" type="textarea" :maxlength="100" :show-word-limit="true" :autosize="{ minRows: 4, maxRows: 10 }" class="el-input-min-width'" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 250px)" :data="crud.data" size="small" row-key="drawingId">
          <el-table-column prop="drawingName" label="视图/模型/图纸类别">
            <template slot-scope="scope">
              <el-input v-if="scope.row.isEdit" v-model="scope.row.drawingName" />
              <span v-else>{{ scope.row.drawingName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="groupId" label="组合">
            <template slot-scope="scope">
              <el-select v-if="scope.row.isEdit" v-model="scope.row.groupId" clearable @change="changeGroupId(scope.row)">
                <el-option v-for="(item,index) in groupList" :key="index" :label="item.groupName" :value="item.groupId" :disabled="item.disabled" />
              </el-select>
              <span v-else>{{ scope.row.groupName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="groupNodeName" label="应用节点" />
          <el-table-column prop="groupSize" label="最少必做量" />
          <el-table-column prop="viewNodeList" label="视图节点">
            <template slot-scope="scope">
              <el-select v-if="scope.row.isEdit" v-model="scope.row.viewNodeList" multiple @change="changeViewNode(scope.row)">
                <el-option v-for="(item,index) in dict.standard_process_node" :key="index" :label="item.label" :value="item.value" />
              </el-select>
              <span v-else>{{ scope.row.viewNodeName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="drawingNodeName" label="图纸节点" />
          <el-table-column prop="nickName" label="更新者" />
          <el-table-column prop="updateTime" label="更新时间" />
          <el-table-column v-if="checkPer(['admin','standardDrawing:edit','standardDrawing:del'])" label="操作" width="150px" align="center">
            <template slot-scope="scope">
              <!-- 编辑状态下显示保存和取消按钮 -->
              <template v-if="scope.row.isEdit">
                <el-button type="text" size="mini" @click="handleSave(scope.row)"><svg-icon icon-class="save-icon" /> 保存</el-button>
                <el-button type="text" size="mini" @click="handleCancel(scope.row)"><svg-icon icon-class="cancel-icon" /> 取消</el-button>
              </template>
              <!-- 非编辑状态下显示编辑和删除按钮 -->
              <template v-else>
                <el-button type="text" size="mini" @click="handleEdit(scope.row)"><svg-icon icon-class="icon-edit" /> 编辑</el-button>
                <el-button class="uifix-table-action-error-btn" type="text" size="mini" icon="el-icon-delete" @click="crud.doDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 配置组合 -->
    <configGroup ref="config" :discipline="discipline" />
    <!-- 日志 -->
    <LogDialog :log-type="logType" :dialog-visible.sync="showLog" />
  </div>
</template>

<script>
import crudStandardDrawing, { edit, exchangeUpdateDrawingSorted } from '@/api/modelQuality/drawingManage'
import { queryGroupOperationForDrawing } from '@/api/modelQuality/standardDrawingRelationGroup'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import crudOperation from '@brotherCrud/CRUD.operation'
import LogDialog from '@/components/logManage/dialog'
import { DRAWING_LOG } from '@/utils/log'
import configGroup from './configGroup'
import Sortable from 'sortablejs'

const defaultForm = { drawingId: null, discipline: null, drawingName: null, createBy: null, updateBy: null, createTime: null, updateTime: null, groupId: null, groupNodeName: null, groupSize: null, viewNodeList: null, drawingNodeName: null }
export default {
  name: 'StandardDrawing',
  components: { crudOperation, LogDialog, configGroup },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['standard_drawing_discipline', 'standard_process_node'],
  cruds() {
    return CRUD({ title: '图纸管理', url: 'api/standardDrawing', idField: 'drawingId', queryOnPresenterCreated: false, query: { page: 0, size: 10000 }, sort: 'drawingId,asc', optShow: { add: true, edit: false, del: false, download: false, reset: false }, crudMethod: { ...crudStandardDrawing }})
  },
  data() {
    return {
      discipline: '',
      groupList: [],
      permission: {
        add: ['admin', 'standardDrawing:add'],
        edit: ['admin', 'standardDrawing:edit'],
        del: ['admin', 'standardDrawing:del']
      },
      rules: {
        drawingName: [
          { required: true, message: '图纸名称不能为空', trigger: 'blur' }
        ]
      },
      showLog: false,
      logType: DRAWING_LOG
    }
  },
  mounted() {
    this.initSortable()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.query.discipline = this.discipline
      return true
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud, form) {
      if (crud.form.drawingId === null) {
        crud.form.discipline = this.discipline
      }
    },
    // 切换左侧节点
    changeItem(item) {
      this.discipline = item.value
      this.crud.toQuery()
    },
    // 组合下拉框
    queryGroupOperationForDrawing(row) {
      const params = {
        standardDiscipline: this.discipline,
        drawingId: row.drawingId
      }
      queryGroupOperationForDrawing(params).then(res => {
        this.groupList = res
      })
    },
    // 切换组合
    changeGroupId(row) {
      if (!row.groupId) {
        row.groupNodeName = ''
        row.groupSize = ''
        return
      }
      const currentGroupId = this.groupList.find(item => item.groupId === row.groupId)
      row.groupNodeName = currentGroupId.groupNodeName
      row.groupSize = currentGroupId.groupSize
    },
    // 切换视图节点
    changeViewNode(row) {
      const drawingNodeList = this.dict.standard_process_node.filter(node => !row.viewNodeList.includes(node.value))
      row.drawingNodeName = drawingNodeList.map(item => item.label).join('、')
    },
    // 编辑
    handleEdit(row) {
      this.queryGroupOperationForDrawing(row)
      this.$set(row, 'isEdit', true)
    },
    // 保存
    handleSave(row) {
      edit(row).then(() => {
        this.$set(row, 'isEdit', false)
        this.crud.toQuery()
      })
    },
    // 取消
    handleCancel(row) {
      this.crud.toQuery()
    },
    // 日志
    toggleShowLog() {
      this.showLog = !this.showLog
    },
    // 配置组合
    configGroup() {
      this.$refs.config.dialog = true
      this.$refs.config.crud.toQuery()
    },
    // 拖拽行
    initSortable() {
      this.$nextTick(() => {
        const tbody = document.querySelector(
          ' .el-table__body-wrapper tbody'
        )
        this.sortable = Sortable.create(tbody, {
          onEnd: ({ newIndex, oldIndex, to, from }) => {
            this.crud.data.splice(newIndex, 0, this.crud.data.splice(oldIndex, 1)[0])
            var newArray = this.crud.data.slice(0)
            this.crud.data = []
            this.$nextTick(function() {
              this.crud.data = newArray
              this.updateList()
            })
          }
        })
      })
    },
    // 调用移动接口
    updateList() {
      const dataList = this.crud.data.map((item) => item)
      exchangeUpdateDrawingSorted(dataList).then(res => {
        this.$message({
          type: 'success',
          message: '移动成功'
        })
      })
    }
  }
}
</script>

<style scoped>
  .item {
    font-size: 13px;
    cursor: pointer;
    padding: 12px;
  }
  .box-card {
    margin-top: 6px;
  }
  .active {
    background-color: var(--admin-table-selected-bg);
    color: var(--ui-theme-color);
  }
</style>
